package com.chaos.eurekaproducer.controller;

import com.chaos.eurekaproducer.EurekaProducerApplication;
import com.chaos.eurekaproducer.redis.JedisUtil;
import com.chaos.eurekaproducer.redis.RedisTemplateUtil;
import com.chaos.eurekaproducer.redis.RedissonUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author liaopeng
 * @title: RedisController
 * @projectName eureka-producer
 * @description: TODO
 * @date 2021/5/18下午4:28
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EurekaProducerApplication.class)
public class RedisController {

    @Autowired
    RedisTemplateUtil redisTemplateUtil;

    @Autowired
    JedisUtil jedisUtil;

    @Autowired
    RedissonUtil redissonUtil;

    @Test
    public void  add(){
        redisTemplateUtil.set("夏夜",18);
    }

    @Test
    public void  testDistributionLock(){
        String uuid = UUID.randomUUID().toString();
        //非可重入锁
        boolean getLock1 = jedisUtil.tryGetDistributedLock("chaos", uuid, 1000);
        System.out.println(getLock1);
        boolean getLock2 = jedisUtil.tryGetDistributedLock("chaos", uuid, 1000);
        System.out.println(getLock2);

        //可重入锁
        boolean xiaye = jedisUtil.tryReentrantLock("xiaye", uuid, 1000);
        System.out.println(xiaye);
        boolean xiaye1 = jedisUtil.tryReentrantLock("xiaye", uuid, 1000);
        System.out.println(xiaye1);
        boolean xiaye2 = jedisUtil.releaseReentrantLock("xiaye", uuid);
    }

    @Test
    public void  testRedissonLock(){
        try {
            redissonUtil.lock("chaos");
            Thread.sleep(41*1000);
            System.out.println("是否持有当前锁："+redissonUtil.isHeldByCurrentThread("chaos"));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            redissonUtil.unlock("chaos");
        }

    }

}
